class DriftBottle {
    constructor() {
        this.bottles = JSON.parse(localStorage.getItem('bottles')) || [];
        this.dailyLimit = 5;
        this.scheduledBottles = JSON.parse(localStorage.getItem('scheduledBottles')) || [];
        this.currentBottle = null;
        this.emailModal = null;
        this.user = null;
        this.loginModal = null;
        this.loginBtn = null;
        this.userInfo = null;
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.init());
        } else {
            this.init();
        }
    }

    init() {
        try {
            this.initElements();
            this.bindEvents();
            this.checkDailyCount();
            this.initFloatingBottles();
            this.initEmailFeature();
            this.initAuthFeature();
            this.initInboxFeature();
            this.checkLoginStatus();
            console.log('漂流瓶应用初始化完成');
        } catch (error) {
            console.error('初始化失败:', error);
        }
    }

    initElements() {
        // 基本元素
        this.throwBtn = this.getElement('throwBottle');
        this.pickBtn = this.getElement('pickBottle');
        this.throwModal = this.getElement('throwModal');
        this.pickModal = this.getElement('pickModal');
        this.closeButtons = document.getElementsByClassName('close');
        this.messageBox = this.getElement('messageBox');
        
        // 定时发送相关元素
        this.enableScheduleCheckbox = this.getElement('enableSchedule');
        this.scheduleInputs = document.querySelector('.schedule-inputs');
        
        // 私发邮件相关元素
        this.emailModal = this.getElement('emailModal');
        
        // 回复相关元素
        this.replyForm = document.querySelector('.reply-form');
        
        // 消息框相关
        if (this.messageBox) {
            this.messageText = this.messageBox.querySelector('.message-text');
        }

        // 绑定定时选项切换事件
        if (this.enableScheduleCheckbox && this.scheduleInputs) {
            this.enableScheduleCheckbox.addEventListener('change', (e) => {
                this.scheduleInputs.style.display = e.target.checked ? 'flex' : 'none';
            });
        }

        this.loginModal = this.getElement('loginModal');
        this.loginBtn = this.getElement('loginBtn');
        this.userInfo = this.getElement('userInfo');
        this.inboxBtn = this.getElement('inboxBtn');
    }

    // 辅助方法：获取元素并处理错误
    getElement(id) {
        const element = document.getElementById(id);
        if (!element) {
            console.warn(`Element with id "${id}" not found`);
        }
        return element;
    }

    bindEvents() {
        if (this.throwBtn) {
            this.throwBtn.addEventListener('click', () => this.showThrowModal());
        }
        
        if (this.pickBtn) {
            this.pickBtn.addEventListener('click', () => this.pickRandomBottle());
        }
        
        if (this.closeButtons) {
            Array.from(this.closeButtons).forEach(btn => {
                btn.addEventListener('click', () => this.closeModals());
            });
        }

        const submitBottle = this.getElement('submitBottle');
        if (submitBottle) {
            submitBottle.addEventListener('click', () => this.throwNewBottle());
        }

        const replyBottle = this.getElement('replyBottle');
        if (replyBottle) {
            replyBottle.addEventListener('click', () => this.replyToBottle());
        }

        window.addEventListener('click', (e) => {
            if (e.target === this.throwModal || e.target === this.pickModal) {
                this.closeModals();
            }
        });
    }

    checkDailyCount() {
        const today = new Date().toDateString();
        const dailyCount = JSON.parse(localStorage.getItem('dailyCount')) || {};
        
        if (dailyCount.date !== today) {
            dailyCount.date = today;
            dailyCount.count = 0;
            localStorage.setItem('dailyCount', JSON.stringify(dailyCount));
        }

        if (dailyCount.count >= this.dailyLimit) {
            this.throwBtn.disabled = true;
            this.throwBtn.textContent = '今日投掷次数已达上限';
            this.showMessage('今日投掷次数已达上限，明天再来吧！');
        }
    }

    showThrowModal() {
        this.throwModal.style.display = 'block';
    }

    closeModals() {
        if (this.throwModal) {
            this.throwModal.style.display = 'none';
        }
        if (this.pickModal) {
            this.pickModal.style.display = 'none';
            
            // 重置捡瓶子相关状态
            const pickScene = this.pickModal.querySelector('.pick-scene');
            if (pickScene) {
                pickScene.classList.remove('active');
            }
        }

        // 重置内容显示
        const bottleContent = document.getElementById('bottleContent');
        const replyButton = document.getElementById('replyBottle');
        const replyForm = document.querySelector('.reply-form');

        if (bottleContent) {
            bottleContent.classList.remove('show');
        }
        
        if (replyForm) {
            replyForm.style.display = 'none';
            const replyMessage = document.getElementById('replyMessage');
            if (replyMessage) {
                replyMessage.value = '';
            }
        }
        
        if (replyButton) {
            replyButton.style.display = 'block';
        }

        // 重置邮件相关状态
        if (this.emailModal) {
            this.emailModal.style.display = 'none';
            const emailTo = document.getElementById('emailTo');
            const emailContent = document.getElementById('emailContent');
            if (emailTo) emailTo.value = '';
            if (emailContent) emailContent.value = '';
        }

        this.currentBottle = null;
    }

    async throwNewBottle() {
        const message = document.getElementById('message').value;
        const email = document.getElementById('email').value;
        
        if (!message.trim()) {
            this.showMessage('请输入内容！');
            return;
        }

        try {
            const response = await fetch('/api/bottle/throw', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message, email })
            });

            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || '扔漂流瓶失败');
            }

            this.showMessage('漂流瓶已成功扔出！');
            this.closeModals();
            document.getElementById('message').value = '';
            document.getElementById('email').value = '';
            
            // 更新每日计数
            await this.checkDailyCount();
        } catch (error) {
            console.error('扔漂流瓶失败:', error);
            this.showMessage(error.message);
        }
    }

    async pickRandomBottle() {
        try {
            const response = await fetch('/api/bottle/pick', {
                method: 'POST'
            });

            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || '捡漂流瓶失败');
            }

            if (data.success && data.bottle) {
                this.showPickedBottle(data.bottle);
            }
        } catch (error) {
            console.error('捡漂流瓶失败:', error);
            this.showMessage(error.message);
        }
    }

    showPickedBottle(bottle) {
        const pickModal = this.getElement('pickModal');
        if (!pickModal) return;

        pickModal.style.display = 'block';
        const bottleContent = this.getElement('bottleContent');
        if (!bottleContent) return;

        // 清除之前的内容
        bottleContent.innerHTML = '';
        
        // 添加新内容
        const messageElement = document.createElement('p');
        messageElement.className = 'message';
        messageElement.textContent = bottle.message;
        
        const timeElement = document.createElement('p');
        timeElement.className = 'time';
        timeElement.textContent = `投掷时间：${new Date(bottle.timestamp).toLocaleString()}`;
        
        bottleContent.appendChild(messageElement);
        bottleContent.appendChild(timeElement);
        
        // 添加渐入效果
        bottleContent.classList.add('show');
        
        // 保存当前瓶子ID用于回复
        this.currentBottleId = bottle.id;

        // 显示回复按钮
        const replyButton = this.getElement('replyBottle');
        if (replyButton) {
            replyButton.style.display = 'block';
            replyButton.classList.add('show');
            // 添加点击事件
            replyButton.onclick = () => this.replyToBottle();
        }

        // 添加关闭事件
        const closeBtn = pickModal.querySelector('.close');
        if (closeBtn) {
            closeBtn.onclick = () => {
                pickModal.style.display = 'none';
                if (replyButton) {
                    replyButton.style.display = 'none';
                    replyButton.classList.remove('show');
                }
                bottleContent.classList.remove('show');
                // 清除回复表单
                const replyForm = pickModal.querySelector('.reply-form');
                if (replyForm) {
                    replyForm.style.display = 'none';
                    replyForm.classList.remove('show');
                    const emailInput = replyForm.querySelector('input[type="email"]');
                    const messageInput = replyForm.querySelector('textarea');
                    if (emailInput) emailInput.value = '';
                    if (messageInput) messageInput.value = '';
                }
            };
        }
    }

    async sendReply(message, email) {
        if (!this.currentBottleId) {
            this.showMessage('无法回复此漂流瓶');
            return;
        }

        try {
            const response = await fetch(`/api/bottle/reply/${this.currentBottleId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message, email })
            });

            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || '回复失败');
            }

            this.showMessage('回复已发送！');
            this.closeModals();
        } catch (error) {
            console.error('回复失败:', error);
            this.showMessage(error.message);
        }
    }

    initFloatingBottles() {
        const bottles = document.querySelectorAll('.floating-bottle');
        const colors = [
            'rgba(173, 216, 230, 0.6)', // 浅蓝
            'rgba(144, 238, 144, 0.6)', // 浅绿
            'rgba(255, 182, 193, 0.6)', // 浅粉
            'rgba(255, 218, 185, 0.6)', // 浅橙
            'rgba(230, 230, 250, 0.6)'  // 浅紫
        ];

        bottles.forEach(bottle => {
            // 随机位置
            const left = this.random(5, 95);
            const top = this.random(10, 90);
            bottle.style.left = `${left}%`;
            bottle.style.top = `${top}%`;

            // 随机颜色
            const color = colors[Math.floor(Math.random() * colors.length)];
            const bottleNeck = bottle.querySelector('.bottle-neck');
            const bottleBody = bottle.querySelector('.bottle-body');
            if (bottleNeck) bottleNeck.style.background = color;
            if (bottleBody) bottleBody.style.background = color;

            // 随机动画参数
            const duration = this.random(6, 12);
            const delay = this.random(-6, 0);
            bottle.style.animationDuration = `${duration}s`;
            bottle.style.animationDelay = `${delay}s`;

            // 随机漂浮范围
            const floatRange = {
                x: this.random(10, 30),
                y: this.random(10, 30),
                rotate: this.random(5, 15)
            };

            // 生成随机漂浮动画
            const style = document.createElement('style');
            const animationName = `float-${Math.random().toString(36).substr(2, 9)}`;
            style.textContent = `
                @keyframes ${animationName} {
                    0%, 100% {
                        transform: translate(0, 0) rotate(0deg);
                    }
                    25% {
                        transform: translate(${-floatRange.x}px, ${floatRange.y}px) rotate(${floatRange.rotate}deg);
                    }
                    50% {
                        transform: translate(0, ${floatRange.y * 2}px) rotate(0deg);
                    }
                    75% {
                        transform: translate(${floatRange.x}px, ${floatRange.y}px) rotate(${-floatRange.rotate}deg);
                    }
                }
            `;
            document.head.appendChild(style);
            bottle.style.animation = `${animationName} ${duration}s infinite ease-in-out ${delay}s`;
        });
    }

    random(min, max) {
        return Math.random() * (max - min) + min;
    }

    // 添加HTML转义方法以防止XSS
    escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // 添加显示消息的方法
    showMessage(text, duration = 2000) {
        if (!this.messageBox || !this.messageText) {
            console.warn('Message elements not initialized');
            return;
        }
        
        this.messageText.textContent = text;
        this.messageBox.classList.add('show');
        
        setTimeout(() => {
            this.messageBox.classList.remove('show');
        }, duration);
    }

    initScheduleCheck() {
        // 每分钟检查一次定时瓶子
        setInterval(() => {
            this.checkScheduledBottles();
        }, 60000);
        
        // 初始化时也检查一次
        this.checkScheduledBottles();
    }

    checkScheduledBottles() {
        const now = Date.now();
        const updatedBottles = [];
        
        this.scheduledBottles.forEach(bottle => {
            if (bottle.status === 'pending' && bottle.scheduleTime <= now) {
                // 发送邮件
                this.sendScheduledEmail(bottle);
                bottle.status = 'sent';
            }
            updatedBottles.push(bottle);
        });

        // 更新存储
        this.scheduledBottles = updatedBottles;
        localStorage.setItem('scheduledBottles', JSON.stringify(updatedBottles));
    }

    async sendScheduledEmail(bottle) {
        try {
            // 这里需要实现实际的邮件发送逻辑
            // 可以调用后端API或使用邮件服务
            const response = await fetch('/api/send-email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    to: bottle.receiverEmail,
                    subject: '你收到一个定时漂流瓶',
                    message: bottle.message,
                    from: bottle.senderEmail || '匿名用户'
                })
            });

            if (!response.ok) {
                throw new Error('邮件发送失败');
            }
        } catch (error) {
            console.error('发送定时邮件失败:', error);
            // 可以添加重试逻辑或失败通知
        }
    }

    isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    showPrivateEmailForm() {
        this.replyForm.style.display = 'none';
        this.privateEmailForm.classList.add('show');
    }

    initEmailFeature() {
        const privateEmailBtn = this.getElement('privateEmail');
        const sendEmailBtn = this.getElement('sendEmail');
        const scheduleCheckbox = this.getElement('emailScheduleEnabled');
        const scheduleInputs = this.getElement('emailScheduleInputs');

        if (!privateEmailBtn || !this.emailModal || !sendEmailBtn) {
            console.warn('Email feature elements not found');
            return;
        }

        // 绑定打开模态框事件
        privateEmailBtn.addEventListener('click', () => {
            if (this.emailModal) {
                this.emailModal.style.display = 'block';
                // 设置最小时间为当前时间
                const scheduleTime = this.getElement('emailScheduleTime');
                if (scheduleTime) {
                    const now = new Date();
                    now.setMinutes(now.getMinutes() + 1);
                    scheduleTime.min = now.toISOString().slice(0, 16);
                    scheduleTime.value = now.toISOString().slice(0, 16);
                }
            }
        });

        // 绑定发送按钮事件
        if (sendEmailBtn) {
            sendEmailBtn.addEventListener('click', () => this.sendPrivateEmail());
        }

        // 绑定定时选项切换事件
        if (scheduleCheckbox && scheduleInputs) {
            scheduleCheckbox.addEventListener('change', (e) => {
                scheduleInputs.style.display = e.target.checked ? 'block' : 'none';
                if (e.target.checked) {
                    scheduleInputs.classList.add('show');
                } else {
                    scheduleInputs.classList.remove('show');
                }
            });
        }

        // 绑定关闭按钮事件
        if (this.emailModal) {
            const closeBtn = this.emailModal.querySelector('.close');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    this.emailModal.style.display = 'none';
                    this.resetEmailForm();
                });
            }

            // 点击模态框外部关闭
            window.addEventListener('click', (e) => {
                if (e.target === this.emailModal) {
                    this.emailModal.style.display = 'none';
                    this.resetEmailForm();
                }
            });
        }
    }

    async sendPrivateEmail() {
        const emailTo = this.getElement('emailTo').value.trim();
        const emailContent = this.getElement('emailContent').value.trim();
        const scheduleEnabled = this.getElement('emailScheduleEnabled').checked;
        const scheduleTime = this.getElement('emailScheduleTime')?.value;

        if (!emailTo || !emailContent) {
            this.showMessage('请填写完整信息！');
            return;
        }

        if (!this.isValidEmail(emailTo)) {
            this.showMessage('请输入有效的邮箱地址！');
            return;
        }

        if (scheduleEnabled && !scheduleTime) {
            this.showMessage('请选择定时发送时间！');
            return;
        }

        try {
            const endpoint = scheduleEnabled ? '/api/schedule-email' : '/api/send-private-email';
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    to: emailTo,
                    content: emailContent,
                    scheduleTime: scheduleEnabled ? new Date(scheduleTime).toISOString() : null
                })
            });

            const data = await response.json();
            if (!response.ok) {
                throw new Error(data.error || '邮件发送失败');
            }

            this.showMessage(scheduleEnabled ? '邮件已设置定时发送！' : '邮件已发送！');
            this.emailModal.style.display = 'none';
            this.resetEmailForm();
        } catch (error) {
            console.error('发送邮件失败:', error);
            this.showMessage(error.message || '发送失败，请稍后重试');
        }
    }

    resetEmailForm() {
        const elements = {
            emailTo: this.getElement('emailTo'),
            emailContent: this.getElement('emailContent'),
            emailScheduleEnabled: this.getElement('emailScheduleEnabled'),
            emailScheduleTime: this.getElement('emailScheduleTime'),
            emailScheduleInputs: this.getElement('emailScheduleInputs')
        };

        // 重置所有表单字段
        if (elements.emailTo) elements.emailTo.value = '';
        if (elements.emailContent) elements.emailContent.value = '';
        if (elements.emailScheduleEnabled) elements.emailScheduleEnabled.checked = false;
        if (elements.emailScheduleTime) elements.emailScheduleTime.value = '';
        if (elements.emailScheduleInputs) {
            elements.emailScheduleInputs.style.display = 'none';
            elements.emailScheduleInputs.classList.remove('show');
        }
    }

    replyToBottle() {
        const replyForm = document.querySelector('.reply-form');
        const replyButton = this.getElement('replyBottle');
        
        if (replyForm && replyButton) {
            replyForm.style.display = 'block';
            replyButton.style.display = 'none';
            
            // 绑定发送回复按钮事件
            const sendReplyButton = this.getElement('sendReply');
            if (sendReplyButton) {
                sendReplyButton.onclick = async () => {
                    const messageInput = this.getElement('replyMessage');
                    const emailInput = this.getElement('replyEmail');
                    
                    if (!messageInput) {
                        console.error('回复消息输入框未找到');
                        return;
                    }
                    
                    const message = messageInput.value.trim();
                    const email = emailInput ? emailInput.value.trim() : '';
                    
                    if (!message) {
                        this.showMessage('请输入回复内容！');
                        return;
                    }
                    
                    await this.sendReply(message, email);
                };
            }
        }
    }

    initAuthFeature() {
        // 登录按钮点击事件
        if (this.loginBtn) {
            this.loginBtn.addEventListener('click', () => {
                if (this.loginModal) {
                    this.loginModal.style.display = 'block';
                }
            });
        }

        // 发送验证码按钮
        const sendCodeBtn = this.getElement('sendCodeBtn');
        if (sendCodeBtn) {
            sendCodeBtn.addEventListener('click', () => this.sendVerifyCode());
        }

        // 登录提交按钮
        const loginSubmit = this.getElement('loginSubmit');
        if (loginSubmit) {
            loginSubmit.addEventListener('click', () => this.login());
        }

        // 退出登录按钮
        const logoutBtn = this.getElement('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => this.logout());
        }

        // 关闭登录模态框
        if (this.loginModal) {
            const closeBtn = this.loginModal.querySelector('.close');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    this.loginModal.style.display = 'none';
                });
            }

            window.addEventListener('click', (e) => {
                if (e.target === this.loginModal) {
                    this.loginModal.style.display = 'none';
                }
            });
        }
    }

    async checkLoginStatus() {
        try {
            const response = await fetch('/api/auth/check');
            const data = await response.json();

            if (data.loggedIn) {
                this.user = data.user;
                this.updateAuthUI(true);
            } else {
                this.updateAuthUI(false);
            }
        } catch (error) {
            console.error('检查登录状态失败:', error);
        }
    }

    async sendVerifyCode() {
        const emailInput = this.getElement('loginEmail');
        const email = emailInput?.value.trim();

        if (!email) {
            this.showMessage('请输入邮箱地址');
            return;
        }

        if (!this.isValidEmail(email)) {
            this.showMessage('请输入有效的邮箱地址');
            return;
        }

        try {
            const response = await fetch('/api/auth/send-code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email })
            });

            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || '发送验证码失败');
            }

            this.showMessage('验证码已发送到您的邮箱');
            
            // 禁用发送按钮60秒
            const sendCodeBtn = this.getElement('sendCodeBtn');
            if (sendCodeBtn) {
                let countdown = 60;
                sendCodeBtn.disabled = true;
                const timer = setInterval(() => {
                    sendCodeBtn.textContent = `${countdown}秒后重试`;
                    countdown--;
                    if (countdown < 0) {
                        clearInterval(timer);
                        sendCodeBtn.disabled = false;
                        sendCodeBtn.textContent = '发送验证码';
                    }
                }, 1000);
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            this.showMessage(error.message || '发送验证码失败');
        }
    }

    async login() {
        const email = this.getElement('loginEmail')?.value.trim();
        const code = this.getElement('verifyCode')?.value.trim();

        if (!email || !code) {
            this.showMessage('请填写完整信息');
            return;
        }

        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email, code })
            });

            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.error || '登录失败');
            }

            this.user = data.user;
            this.updateAuthUI(true);
            this.loginModal.style.display = 'none';
            this.showMessage('登录成功');
        } catch (error) {
            console.error('登录失败:', error);
            this.showMessage(error.message || '登录失败');
        }
    }

    async logout() {
        try {
            const response = await fetch('/api/auth/logout', {
                method: 'POST'
            });

            if (!response.ok) {
                throw new Error('退出登录失败');
            }

            this.user = null;
            this.updateAuthUI(false);
            this.showMessage('已退出登录');
        } catch (error) {
            console.error('退出登录失败:', error);
            this.showMessage('退出登录失败');
        }
    }

    updateAuthUI(isLoggedIn) {
        if (isLoggedIn && this.user) {
            if (this.loginBtn) this.loginBtn.style.display = 'none';
            if (this.userInfo) {
                this.userInfo.style.display = 'block';
                const emailSpan = this.userInfo.querySelector('.user-email');
                if (emailSpan) emailSpan.textContent = this.user.email;
            }
            if (this.inboxBtn) this.inboxBtn.style.display = 'flex';
        } else {
            if (this.loginBtn) this.loginBtn.style.display = 'block';
            if (this.userInfo) this.userInfo.style.display = 'none';
            if (this.inboxBtn) this.inboxBtn.style.display = 'none';
        }
    }

    initInboxFeature() {
        // 初始化收件箱按钮点击事件
        const inboxBtn = this.getElement('inboxBtn');
        const inboxModal = this.getElement('inboxModal');
        
        if (inboxBtn && inboxModal) {
            inboxBtn.addEventListener('click', () => {
                this.openInbox();
            });

            // 关闭按钮事件
            const closeBtn = inboxModal.querySelector('.close');
            if (closeBtn) {
                closeBtn.addEventListener('click', () => {
                    inboxModal.style.display = 'none';
                });
            }

            // 点击外部关闭
            window.addEventListener('click', (e) => {
                if (e.target === inboxModal) {
                    inboxModal.style.display = 'none';
                }
            });
        }

        // 定期检查新消息
        if (this.user) {
            this.checkNewMessages();
            setInterval(() => this.checkNewMessages(), 60000); // 每分钟检查一次
        }
    }

    async openInbox() {
        if (!this.user) {
            this.showMessage('请先登录');
            return;
        }

        const inboxModal = this.getElement('inboxModal');
        if (!inboxModal) return;

        try {
            const response = await fetch('/api/messages/inbox');
            const messages = await response.json();

            if (!response.ok) {
                throw new Error(messages.error || '获取消息失败');
            }

            const inboxList = inboxModal.querySelector('.inbox-list');
            if (inboxList) {
                inboxList.innerHTML = this.renderMessages(messages);
            }

            inboxModal.style.display = 'block';
            
            // 标记所有消息为已读
            this.markAllAsRead();
        } catch (error) {
            console.error('打开收件箱失败:', error);
            this.showMessage('获取消息失败');
        }
    }

    renderMessages(messages) {
        if (!messages.length) {
            return '<div class="no-messages">暂无消息</div>';
        }

        return messages.map(msg => `
            <div class="inbox-item ${msg.isRead ? '' : 'unread'}" data-id="${msg.id}">
                <div class="message-header">
                    <span class="message-type">${this.getMessageTypeText(msg.type)}</span>
                    <span class="message-time">${new Date(msg.createdAt).toLocaleString()}</span>
                </div>
                <div class="message-content">${this.escapeHtml(msg.content)}</div>
                ${msg.from ? `<div class="message-from">来自: ${this.escapeHtml(msg.from)}</div>` : ''}
            </div>
        `).join('');
    }

    getMessageTypeText(type) {
        const types = {
            'bottle_reply': '漂流瓶回复',
            'private_email': '私信',
            'system': '系统消息'
        };
        return types[type] || '其他消息';
    }

    async checkNewMessages() {
        try {
            const response = await fetch('/api/messages/unread-count');
            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error);
            }

            this.updateUnreadCount(data.count);
        } catch (error) {
            console.error('检查新消息失败:', error);
        }
    }

    updateUnreadCount(count) {
        const unreadCount = this.inboxBtn?.querySelector('.unread-count');
        if (unreadCount) {
            if (count > 0) {
                unreadCount.textContent = count > 99 ? '99+' : count;
                unreadCount.style.display = 'flex';
            } else {
                unreadCount.style.display = 'none';
            }
        }
    }

    async markAllAsRead() {
        try {
            const response = await fetch('/api/messages/mark-all-read', {
                method: 'POST'
            });

            if (!response.ok) {
                throw new Error('标记已读失败');
            }

            this.updateUnreadCount(0);
        } catch (error) {
            console.error('标记已读失败:', error);
        }
    }
}

// 等待 DOM 加载完成后再初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.driftBottle = new DriftBottle();
}); 